<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>打字机效果</title>
    <script src="../../../jquery.min.js"></script>


</head>
<body>


<div id='text'></div>


<script>
    window.onload = function () {
        let element = $('#text');

        let str = '使用JS实现 一个打字机字 符输出 效果使用JS实现一个打字机字符输出效果使用JS实现一 个打字机字符输出效果使用 JS实现一个打字机字符输出效果';
        let speed = 50;
        let typer = function (opts) {
            let arr = [];
            for (let i = 0; i < opts.str.length; i++) {
                arr.push(opts.str[i])
            }
            let text1 = '';
            let num = 0;
            let timer = setInterval(function () {
                if (num < arr.length) {
                    text1 += arr[num];
                    if (opts.element instanceof jQuery) {
                        opts.element.html(text1);
                    } else {
                        opts.element.innerHTML = text1;
                    }
                    num++;
                } else {
                    clearInterval(timer);
                    opts.callback();
                }
            }, opts.speed)
        };
        typer({
            element,
            str,
            speed,
            callback: function() {
                alert('打印完成');
            }
        });
    };
</script>
</body>
</html>